import {
  ChangeDetectionStrategy,
  Component,
  EventEmitter,
  Input,
  Output,
  ViewEncapsulation,
} from '@angular/core'
import { AdAnimations } from 'monk-design/animations'
import { AdTreeData } from './tree.interface'

@Component({
  selector: 'ad-tree-view',
  template: `
    <ng-container *ngFor="let upperNode of adTreeNode">
      <ng-template
        [ngTemplateOutlet]="nodeTemplate"
        [ngTemplateOutletContext]="{ $implicit: setLevel(upperNode, 0) }"
      ></ng-template>
    </ng-container>
    <ng-template #nodeTemplate let-treeNode>
      <ad-tree-node-provider [adTreeData]="treeNode">
        <ad-tree-node
          [class.ad-tree-node-selected]="selectId === treeNode.id"
          (click)="clickTreeNode(treeNode)"
        >
          <img
            class="ad-tree-node-icon"
            [src]="
              '/assets/monk-design/tree/ad-tree-node-' +
                (treeNode.expanded ? 'expanded' : 'collapsed') +
                '-icon.png' | resource
            "
            alt=""
          />
          <ad-tree-node-name [name]="treeNode.name"></ad-tree-node-name>
        </ad-tree-node>
      </ad-tree-node-provider>
      <div [@expandCollapse]="treeNode.expanded ? 'expanded' : 'collapsed'">
        <ng-container *ngFor="let lowerNode of treeNode.children">
          <ng-container
            [ngTemplateOutlet]="nodeTemplate"
            [ngTemplateOutletContext]="{ $implicit: setLevel(lowerNode, treeNode.level) }"
          ></ng-container>
        </ng-container>
      </div>
    </ng-template>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  animations: [AdAnimations.expandCollapse],
  host: {
    '[class.ad-tree]': 'true',
  },
})
export class AdTreeComponent {
  @Input() selectId: string = null
  @Output() selectNodeChange: EventEmitter<string> = new EventEmitter()
  adTreeNode: any[] = [
    {
      name: '12132',
      expanded: true,
      children: [
        {
          name: '222',
        },
        {
          name: '222',
        },
        {
          name: '222',
        },
        {
          name: '222222222222222222222222222222222222222222222',
        },
        {
          name: '222',
        },
        {
          name: '222',
        },
      ],
    },
    {
      name: '12132',
    },
  ]

  public clickTreeNode(treeNode: AdTreeData) {
    if (treeNode.children?.length > 0) {
      treeNode.expanded = !treeNode.expanded
    }
    this.setSelectId(treeNode.id)
  }

  public setSelectId(id) {
    if (this.selectId === id) {
      return
    }
    this.selectId = id
    this.selectNodeChange.emit(this.selectId)
  }

  public cancelSelected() {
    this.selectId = null
  }

  /**
   * 设置节点等级
   * @param node
   * @param level
   * @returns
   */
  public setLevel(node, level) {
    node.level = level + 1
    return node
  }
}
